<?php

namespace App\Admin\Controllers\Stocking;


use App\Importer\Basics\BImporter;
use App\Importer\Stocking\Sku\SkuImporter;
use App\Jobs\Stocking\JpEstimateJob;
use App\Jobs\Stocking\JpSkuRatioJob;
use App\Models\Basics\SysPlat;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Models\SsBasic\JpClassifyEstimate;
use App\Models\SsBasic\JpSkuEstimate;
use App\Models\SsBasic\JpStockingSkuRatio;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class JpSkuUploadController extends AdminController{

    protected $title = '上传文件';

    protected function grid()
    {
        $type = request('type');
        return view("stocking.jp-sku.upload.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    /**
     * JP平台销售比例
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importRatio(UploadedFile $file){
        try{
            $data = Excel::toArray(new SkuImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $item = [];
            foreach($data as $row){
                $count++;
                $_plat = $row[0] ? trim($row[0]) : '';
                $_sku = $row[1] ? trim($row[1]) : '';
                $_ratio = $row[2] ? trim($row[2]) : 0;
                if(!$_plat || !$_sku){
                    $errors[$count] = ',必填项为空';
                    continue;
                }

                if (strtoupper($_plat) == strtoupper(SysPlat::PLAT_AMAZON_NAME)) {
                    $platId = SysPlat::PLAT_AMAZON;  //Amazon
                }elseif(strtoupper($_plat) == strtoupper(SysPlat::PLAT_RAKUTEN_NAME)){
                    $platId = SysPlat::PLAT_RAKUTEN; //Rakuten
                }else{
                    $errors[$count] = $_plat.',系统不存在该平台(JP)';
                    continue;
                }
                $key = $platId.'_'.$_sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = ',重复记录';
                    continue;
                }

                $pSkuId = ProductSku::getValueByCode($_sku,'id');
                if(!$pSkuId){
                    $errors[$count] = $_sku.',系统不存在该sku';
                    continue;
                }

                DB::beginTransaction();
                $areaPsku = $platId.'_'.$pSkuId;
                $skuRatio = JpStockingSkuRatio::query()->firstOrNew(['area_psku' => $areaPsku]);
                $skuRatio->ratio = (float)$_ratio;
                if($skuRatio->save()){
                    $item[] = $skuRatio;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }

            if(!empty($item)){
                JpSkuRatioJob::dispatch($item);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    /**
     * JP平台品类预估
     * @param UploadedFile $file
     * @return array|\Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    private function _importEstimate(UploadedFile $file){
        try{

            $data = Excel::toArray(new BImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $item = [];
            foreach($data as $row){
                $count++;
                $_plat = $row[0] ? trim($row[0]) : '';
                $_classify = $row[1] ? trim($row[1]) : '';
                $j = 2;
                for($i = 0; $i < JpSkuEstimate::ESTIMATE_NUM; $i++){
                    ${'estimate_num'.$i} = is_null($row[$j]) ? null : trim($row[$j]);
                    $j++;
                }
                if(!$_plat || !$_classify){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                if (strtoupper($_plat) == strtoupper(SysPlat::PLAT_AMAZON_NAME)) {
                    $platId = SysPlat::PLAT_AMAZON;  //Amazon
                }elseif(strtoupper($_plat) == strtoupper(SysPlat::PLAT_RAKUTEN_NAME)){
                    $platId = SysPlat::PLAT_RAKUTEN; //Rakuten
                }else{
                    $errors[$count] = $_plat.',系统不存在该平台(JP)';
                    continue;
                }
                $key = $platId.'_'.$_classify;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = ',重复记录';
                    continue;
                }

                $classifyId = ProductClassify::getIdByTitle($_classify);
                if(!$classifyId){
                    $errors[$count] = $_classify.',系统不存在该品类';
                    continue;
                }

                //JP平台品类预估
                $classifyEstimate = JpClassifyEstimate::query()->firstOrNew([
                    'plat_id' => $platId,
                    'classify_id' => $classifyId
                ]);
                for($i = 0; $i < JpSkuEstimate::ESTIMATE_NUM; $i++){
                    if(!is_null(${'estimate_num'.$i})){
                        $classifyEstimate->{'estimate_num'.$i} = ${'estimate_num'.$i};
                    }
                }
                DB::beginTransaction();
                if($classifyEstimate->save()){
                    $item[] = $classifyEstimate;
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }

            if(!empty($item)){
                //备货预估（JP）
                JpEstimateJob::dispatch($item);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            DB::rollBack();
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
